<?
class User extends CI_Model
{
	public $id = 0;
	public $data = null;
	public $service = false;
	var $sessExpiration = 0;

	public static $roles = array(
		1 => 'Добавление статей',
		2 => 'Редактирование/утверждение чужих статей',
		3 => 'Редактирование пользователей',
		4 => 'Добавление/редактирование страниц',
		5 => 'Редактирование блоков',
		6 => 'Шаблоны писем/рассылки',
		7 => 'Редактирование комментариев',
		8 => 'Просмотр статей',
	);
	
	function __construct()
	{
		parent::__construct();
		$this->session->sess_expiration = $this->getSessExpiration();
		$this->checkSession();
	}
	
	function checkSession()
	{
		// diePR($this->session->all_userdata());
		$this->db->where('id', $this->session->userdata('id'));
		$this->db->where('pHash', $this->session->userdata('hash'));
		$res = $this->db->get('user')->row();
		if ($res)
		{
			$this->data = $res;
			$this->id = $res->id;
			$this->service = false;
			return true;
		}
		else
			return false;
	}
	
	function startSession($email)
	{
		if (is_numeric($email))
			$this->db->where('id', $email);
			else
			$this->db->where('pEmail', $email);
		
		if (!($res = $this->db->get('user')->row()))
			return false;
		
		$this->session->set_userdata(array(
			'id' => $res->id,
			'hash' => $res->pHash,
			'service' => false
		));
	}
	
	function startSSession($data)
	{
		$this->session->set_userdata($data);
	}

	function checkUser($email, $hash = false, $result = false)
	{
		$this->db->where('pEmail', $email);
		if ($hash)
			$this->db->where('pHash', $hash);
		if ($result)
			return $this->db->get('user')->row();
			else
			return (($this->db->get('user')->num_rows)>0);
	}
	
	function get($id)
	{
		$this->db->where('id', $id);
		return $this->db->get('user')->row();
	}
	
	function getUsernameById($id)
	{
		$this->db->where('id', $id);
		return $this->db->get('user')->row()->pName;
	}
	
	function getUsernamesByIds($id = array())
	{
		if (!is_arr($id))
			return array();
		$this->db->where_in('id', $id);
		$res = $this->db->get('user')->result();
		if (!$res)
			return array();
		$exp = array();
		foreach ($res as $val)
			$exp[$val->id] = $val->pName;
		return $exp;
	}
	
	function logout()
	{
		$this->session->sess_destroy();
	}
	
	function setRegEmail($data)
	{
		if (empty($data['login']) || empty($data['name']) || empty($data['reg_password']) || empty($data['reg_repassword']))
			return 1;
		
		$data = array_map('trim', $data);

		if ($data['reg_password'] !== $data['reg_repassword']) return 2;

		if ($this->db->where('pEmail', $data['login'])->count_all_results('user'))
			return 3;

		$ins = array(
			'pEmail' => $data['login'],
			'pHash' => md5($data['login'].$data['reg_password']),
			'pName' => $data['name'],
			'pCode' => md5($data['login'].now())
		);
		
		$user = $this->db->where('pEmail', $data['login'])->get('reg_user')->row();
		if ($user)
			$this->db->where('id', $user->id)->update('reg_user', $ins);
			else
			$this->db->insert('reg_user', $ins);

		if (empty($this->mail))
			$this->load->model('email_model', 'mail');
		
		$text = 'Чтобы подтвердить регистрацию пройдите по <a href="'.base_url().'registration/activate/'.$ins['pCode'].'">этой ссылке</a>';
		
		return $this->mail->sendTemplateEmail($data['login'], 'registration', $ins)?0:4;
	}
	
	function add($data)
	{
		if (empty($_POST['login']) || empty($_POST['name']) || empty($_POST['reg_password']) || empty($_POST['reg_repassword']))
			return false;
		
		if ($data['reg_password'] !== $data['reg_repassword']) return false;
		
		$user = $this->db->where('pEmail', $data['login'])->get('user')->row();
		if (!empty($user))
			return false;
		
		$ins = array(
			'pEmail' => $data['login'],
			'pHash' => md5($data['login'].$data['reg_password']),
			'pName' => $data['name'],
			'dReg' => now(),
			'pKey' => md5(uniqid())
		);
		
		$this->db->insert('user', $ins);
		return $this->db->insert_id();
	}

	function checkSocAuth($soc, $uid)
	{
		if (!in_array($soc, array('vk', 'fb', 'twitter', 'mailru', 'ok')))
			return false;

		$this->db->where('pMethod', $soc);
		$this->db->where('tUid', $uid);
		$res = $this->db->get('user_auth')->row();

		if ($res)
		{
			$this->userId = $res->tUser;
			$this->session->set_userdata(array(
				'id' => $res->tUser,
				'hash' => '',
				'service' => $soc
			));
			return $res->tUser;
		}

		return false;
	}

	function socAuth($soc, $uid, $user = NULL)
	{
		if (!in_array($soc, array('vk', 'fb', 'twitter', 'mailru', 'ok')))
			return false;

		$this->db->where('pMethod', $soc);
		$this->db->where('tUid', $uid);
		$res = $this->db->get('user_auth')->row();

		if ($res)
		{
			$userId = $res->tUser;
		}
		else
		{
			//diepr($user);
			$inserto = array(
				'pName' => $user['pName'],
				'dReg' => now(),
				'pEmail' => '',
				'pHash' => '',
				'pKey' => md5(uniqid()),
			);
			
			if (!empty($user['pEmail']))
				$inserto['pEmail'] = $user['pEmail'];
			
			$this->db->insert('user', $inserto);

			$userId = $this->db->insert_id();

			$this->db->insert('user_auth', array(
				'tUser' => $userId,
				'pMethod' => $soc,
				'tUid' => $uid,
				'pLink' => (isset($user['pLink']))?$user['pLink']:''
			));
		}
		
		$this->userId = $userId;

		if (isset($user['token']))
			$this->session->set_userdata('token', $user['token']);

		$this->session->set_userdata(array(
			'id' => $userId,
			'hash' => '',
			'service' => $soc
		));

		return (bool)$res;
	}
	/*************************************************************************/
	
	function addUserByCode($code)
	{
		$user = $this->db->select('pEmail, pHash, pName')->where('pCode', $code)->get('reg_user')->row();
		
		if (!$user)
			return false;
		
		$this->db->where('pCode', $code)->delete('reg_user');
		
		if ($this->db->where('pEmail', $user->pEmail)->count_all_results('user'))
			return false;
		$user->dReg = now();
		
		return ($this->db->insert('user', $user))?$user->pEmail:false;
		
	}
	
	function checkRight($right='')
	{
		if (!$this->id)
			return false;

		if ($this->data->pAdmin)
			return true;
		
		if (empty($this->data->pModer))
			return false;
		
		return (strpos($this->data->pModer, (string)$right) !== false);
	}
	
	function isAdmin()
	{
		if (!$this->id)
			return false;

		return (bool)($this->data->pAdmin);
	}

	function addNewPasswordRestore($email, $code)
	{
		$this->db->where('pEmail', $email)->delete('password_recovery');

		return $this->db->insert('password_recovery', array(
			'pEmail' => $email,
			'pCode' => $code,
			'dCreated' => now()
		));
	}

	function checkPasswordRestoreCode($code)
	{
		return $this->db->where('pCode', $code)->get('password_recovery')->row();
	}

	function setNewPassword($email, $password)
	{
		$user = $this->db->where('pEmail', $email)->get('user')->row();
		if (!$user)
			return false;

		return $this->db->where('id', $user->id)->update('user', array('pHash' => md5($user->pEmail.$password)));
	}

	function removeCode($code)
	{
		$this->db->where('pCode', $code)->delete('password_recovery');
	}

	function getSessExpiration()
	{
		return $this->sessExpiration = $this->db->where('pKey', 'sessExpiration')->get("settings")->row()->pVal;
	}

	function getSocsByUserId($id=0)
	{
		return $this->db->where('tUser', $id)->get('user_auth')->result();
	}

	function getUsersCount()
	{
		return $this->db->count_all_results('user');
	}
}